<?php
namespace App\Api\Controllers\User;

use App\Api\Controllers\BaseController;
use App\Models\AlipayAppOauthUsers;
use App\Models\DlbStore;
use App\Models\DlbStoreUpload;
use App\Models\EasypayaStore;
use App\Models\EasypayConfig;
use App\Models\EasypayStore;
use App\Models\HltxStore;
use App\Models\HkrtStore;
use App\Models\HStore;
use App\Models\LianfuyoupayStores;
use App\Models\LinkageStores;
use App\Models\Merchant;
use App\Models\MerchantStore;
use App\Models\MyBankStore;
use App\Models\MyBankStoreTem;
use App\Models\NewLandStore;
use App\Models\Order;
use App\Models\Store;
use App\Models\StoreMonthOrder;
use App\Models\StorePayWay;
use App\Models\TfStore;
use App\Models\User;
use App\Models\VbillaStore;
use App\Models\VbillStore;
use App\Models\WeixinaStore;
use App\Models\WeixinStore;
use App\Services\PrintSqlService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Mybank\Mybank;

class SelectController extends BaseController
{
    //下级拓展码
    public function s_code_url(Request $request)
    {
//        $s_code = $request->get('s_code', '');
//        $user_info = User::where('s_code', $s_code)
//            ->where('is_delete', '0')
//            ->first();
//        if (!$user_info) {
//            $message = '用户不存在或状态被禁用';
//             return view('errors.page_errors', compact('message'));
//        }
//        $data = [
//            'pid' => $user_info->id,
//            'pid_name' => $user_info->name,
//            'level' => $user_info->level + 1,
//            'profit_ratio' => $user_info->sub_profit_ratio
//        ];
//
//        return view('expansioncode.wechat', compact('data'));

        $message = '暂时无法添加,请使用其他方式';
        return view('errors.page_errors', compact('message'));
    }

    public function sub_code_url(Request $request)
    {
        $message = '暂时无法添加,请使用其他方式';
        return view('errors.page_errors', compact('message'));
    }


    // 代理流水排行
    public function user_trade_rank(Request $request){
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        // 获取传递的参数
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');
        $sub_user_id = $request->get('user_id', '');

        if(empty($sub_user_id)){
            $sub_user_id = $user_id;
        }
        $user_ids = DB::table('users')->where('pid', $user_id)->select('id','name')->get(); // 所有下级代理

        if(empty($time_start)){
            $time_start = date('Y-m-d', time());
        }
        if(empty($time_end)){
            $time_end = date('Y-m-d', time());
        }
        if ($time_start != $time_end) {
            if ($time_start > $time_end) {
                return json_encode([
                    'status' => 2,
                    'message' => '开始时间不能超过结束时间'
                ]);
            }
        }
        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        if ($date > $day) {
            return json_encode([
                'status' => 2,
                'message' => "时间筛选不能超过 $day 天"
            ]);
        }
        if($time_start >= date("Y-m-d",strtotime("+1 day"))){
            return json_encode([
                'status' => 2,
                'message' => '开始时间不能超过今天'
            ]);
        }

        $where = [];
        $where1 = [];

        $where[] = ['created_at', '>=', date('Y-m-d 00:00:00', time())];
        $where[] = ['created_at', '<=', date('Y-m-d 23:59:59', time())];

        $where1[] = ['settling_day', '>=', $time_start];
        $where1[] = ['settling_day', '<=', $time_end];

        foreach ($user_ids as $k=>$v){
            $sub_ids = $this->getSubIds($v->id);

            if($time_start >= date('Y-m-d', time())){ // 查今天
                $users[$k]['user_id'] = $v->id;
                $users[$k]['user_name'] = $v->name;
                $users[$k]['total_amount'] = DB::table('orders')->whereIn('pay_status', [1])->where($where)->whereIn('user_id', $sub_ids)->sum('total_amount');

            }else{ // 查每日汇总表
                $users[$k]['user_id'] = $v->id;
                $users[$k]['user_name'] = $v->name;

                $users[$k]['total_amount'] = DB::table('company_day_commission')->where($where1)->where('user_id', $v->id)->sum('total_amount');
            }
        }

        $data = array_column($users, 'total_amount');
        array_multisort($data, SORT_DESC, $users); // 代理按金额排序


        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($users);
    }


    //门店交易统计（交易榜）
    // public function ranking(Request $request){
    //     try {
    //         $user = $this->parseToken(); //用户信息
    //         $user_id = $request->get('user_id', '');
    //         $type = $request->get('type', '1'); //排序：1-交易笔数,由大到小;2-交易笔数由小到大;3-交易金额由大到小;4-交易金额由小到大
    //         $time_start = $request->get('time_start', '');
    //         $time_end = $request->get('time_end', '');

    //         //限制时间
    //         if (empty($time_end)) {
    //             $time_end = date('Y-m-d H:i:s', time());
    //         } else {
    //             if ($time_start != $time_end) {
    //                 $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
    //                 if (!$date) {
    //                     return json_encode([
    //                         'status' => 2,
    //                         'message' => '开始时间不能超过结束时间'
    //                     ]);
    //                 }
    //             }
    //             $time_end = "$time_end 23:59:59";
    //         }
    //         $time_start = "$time_start 00:00:00";

    //         $user_ids = [];
    //         if ($user_id) {
    //             $user_ids = [
    //                 ['user_id' => $user_id]
    //             ];
    //             $user_ids = $this->getSubIds($user_id);
    //         } else {
    //             $user_ids = $this->getSubIds($user->user_id);
    //         }

    //         if ($type == "1" || $type == "2") {
    //             $sort = 'desc';
    //             if ($type == "2") {
    //                 $sort = 'asc';
    //             }
    //             $order_field = "COUNT(`total_amount`)";
    //         } else {
    //             $sort = 'desc';
    //             if ($type == "4") {
    //                 $sort = 'asc';
    //             }

    //             $order_field = "SUM(`total_amount`)";
    //         }

    //         $obj = Order::query()->select([
    //             'store_id',
    //             'store_name',
    //             DB::raw("SUM(`total_amount`) AS `total_amount`, COUNT(`total_amount`) AS `total_count`"),
    //             DB::raw("SUM(IF(`ways_source`='alipay', `total_amount`, 0)) AS `alipay_amount`"),
    //             DB::raw("COUNT(IF(`ways_source`='alipay', true, null)) AS `alipay_count`"),
    //             DB::raw("SUM(IF(`ways_source`='weixin', `total_amount`, 0)) AS `weixin_amount`"),
    //             DB::raw("COUNT(IF(`ways_source`='weixin', true, null)) AS `weixin_count`"),
    //             DB::raw("COUNT(IF(`pay_method`='alipay_face', true, null)) as `alipay_face_count`"),
    //             DB::raw("COUNT(IF(`pay_method`='weixin_face', true, null)) as `weixin_face_count`")
    //         ])
    //             ->whereIn('user_id', $user_ids)
    //             ->where('pay_status', 1)
    //             ->where('created_at', '>', $time_start)
    //             ->where('created_at', '<', $time_end)
    //             ->groupBy('store_id')
    //             ->orderBy(DB::raw($order_field), $sort);

    //         $this->t = $obj->paginate(10)->total();
    //         $data = $this->page($obj)->get();
    //     } catch (\Exception $exception) {
    //         return json_encode([
    //             'status' => -1,
    //             'message' => $exception->getMessage().' | '.$exception->getFile().' | '.$exception->getLine()
    //         ]);
    //     }

    //     $this->status = 1;
    //     $this->message = '数据返回成功';
    //     return $this->format($data);
    // }

    // 门店交易统计（交易榜）
    function ranking(Request $request){
        try {
            $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');

            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => "时间筛选不能超过 $day 天"
                ]);
            }

            if( empty($time_end) ){
                $time_end = date('Y-m-d H:i:s', time());
            } else {
                if ($time_start != $time_end) {
                    $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                    if (!$date) {
                        return json_encode([
                            'status' => 2,
                            'message' => '开始时间不能超过结束时间'
                        ]);
                    }
                }
            }

            if($time_start >= date('Y-m-d', time()) || $time_end >= date('Y-m-d', time()) ){
                return json_encode([
                    'status' => 2,
                    'message' => '不支持查询今天的统计数据'
                ]);
            }

            $user_ids = $this->getSubIds($user_id);

            $obj = DB::table('stores')->where('pid', '=', 0)->whereIn('user_id', $user_ids)->select('id', 'store_id', 'store_name'); // 门店列表
            $this->t = $obj->paginate(10)->total();
            $store = $this->page($obj)->get();

            $data = [];
            // if( $time_start == date('Y-m-d', time()) ){ // 今天
            //     $where[] = [ 'created_at', '>=', date('Y-m-d 00:00:00', time()) ];
            //     $where[] = [ 'created_at', '<=', date('Y-m-d 23:59:59', time()) ];

            //     foreach($store as $k => $v){
            //         $p_stores = DB::table('stores')->where('pid', $v->id)->select('store_id')->get(); // 查找总店下的分店
            //         if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
            //             $store_ids[0] = $v->store_id;
            //             $p_stores = json_decode($p_stores, true);
            //             foreach($p_stores as $k1 => $v1){
            //                 $store_ids[] = $v1['store_id'];
            //             }
            //         }else{
            //             $store_ids[0] = $v->store_id;
            //         }

            //         $data[$k]['store_name'] = $v->store_name;
            //         $obj = DB::table('orders')->whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6]);

            //         $data[$k]['store_amount'] = $obj->sum('total_amount');
            //         $data[$k]['store_order_count'] = $obj->count('total_amount');
            //         $data[$k]['weixin_amount'] = DB::table('orders')->whereIn('store_id', $store_ids)->where('ways_source', 'weixin')->where($where)->whereIn('pay_status', [1, 6])->sum('total_amount');
            //         $data[$k]['alipay_amount'] = DB::table('orders')->whereIn('store_id', $store_ids)->where('ways_source', 'alipay')->where($where)->whereIn('pay_status', [1, 6])->sum('total_amount');
            //         unset($store_ids);
            //     }
            // }else{
                $where[] = ['settling_day', '>=', $time_start];
                $where[] = ['settling_day', '<=', $time_end];

                foreach($store as $k => $v){
                    $data[$k]['store_name'] = $v->store_name;
                    $data[$k]['store_amount'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('total_amount');
                    $data[$k]['store_order_count'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('total_num');
                    $data[$k]['weixin_amount'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('wx_total_amount');
                    $data[$k]['alipay_amount'] = DB::table('company_day_commission')->where($where)->where('store_id', $v->store_id)->where('user_id', $user_id)->sum('zfb_total_amount');
                }
            // }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine()
            ]);
        }
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($data);
    }

    //平安标记
    function pingan(Request $request){
        try {
            $user = $this->parseToken(); //用户信息
            $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息

            $type = $request->get('type', '1'); // 0:未标记 1:使用插件 2:不使用插件

            $obj = DB::table('pingan_stores')->where('type',$type);
            $this->t = $obj->paginate(10)->total();
            $data = $this->page($obj)->get();
            foreach ($data as $k=>$v){
                $store=DB::table('stores')->where('store_id', $v->store_id)->first(); // 门店列表
                $data[$k]->store_name=$store->store_name;
                if($v->type==0){
                    $data[$k]->status_name='未标记';
                }else if($v->type==1){
                    $data[$k]->status_name='使用插件';
                }else if($v->type==2){
                    $data[$k]->status_name='不使用插件';
                }
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine()
            ]);
        }
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($data);
    }

    //平安标记
    function pingan_plug(Request $request){
        try {
            $user = $this->parseToken(); //用户信息
            $id=$request->get('id', '');
            $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息

            $pingan_store = DB::table('pingan_stores')->where('id', $id)->first();
            $type = $request->get('type', '1'); // 0:未标记 1:使用插件 2:不使用插件
            if($type==1){
                $obj = new \App\Api\Controllers\lianfu\PayController();

                $pingan_data['merchant_id']=$pingan_store->merchant_id;

                foreach (array_filter($pingan_data) as $k => $v){
                    $Parameters[$k] = $v;
                }
                $buff = "";
                ksort($Parameters);
                foreach ($Parameters as $k => $v) {
                    $buff .= $k . "=" . $v . "&";
                }
                $String = '';
                if (strlen($buff) > 0) {
                    $String = substr($buff, 0, strlen($buff) - 1);
                }
                $String = $String . $pingan_store->appsecret;
                $re=hash('sha256', $String, true);
                $String = strtoupper(bin2hex($re));
                $appid=$pingan_store->appid;
                $json='{"appid":"'."$appid".'"'.',"timeStamp":"'.time().'000'.'"'.',"data":'.stripslashes(json_encode($pingan_data,JSON_UNESCAPED_SLASHES)).',"sign":"'.$String.'"'.'}';
                $return = $obj->postpingan($json);
                if($return==1){
                    DB::table('pingan_stores')->where('id', $id)->update(array('type'=>1));
                    return json_encode([
                        'status' => 1,
                        'message' =>'确定成功'
                    ]);
                }else{
                    return json_encode([
                        'status' => -1,
                        'message' => '确定失败'
                    ]);
                }
            }else if($type==2){
                 DB::table('pingan_stores')->where('id', $id)->update(array('type'=>2));
                 return json_encode([
                    'status' => 1,
                    'message' =>'确定成功'
                ]);
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine()
            ]);
        }
    }

    // 渠道通道汇总
    function usercompany(Request $request){
        try {
            $user = $this->parseToken(); //用户信息
            $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
            //获取传递的参数
            $company_id = $request->get('company_id', ''); // 排序：1-交易笔数,由大到小;2-交易笔数由小到大;3-交易金额由大到小;4-交易金额由小到大
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');
            $sub_user_id = $request->get('user_id', '');
            if(empty($sub_user_id)){
                $sub_user_id=$user_id;
            }

            if(empty($time_start)){
                $time_start=date('Y-m-d',time());
            }
            if(empty($time_end)){
                $time_end=date('Y-m-d',time());
            }
            if ($time_start != $time_end) {
                $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                if (!$date) {
                    return json_encode([
                        'status' => 2,
                        'message' => '开始时间不能超过结束时间'
                    ]);
                }
            }
            // //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => "时间筛选不能超过 $day 天"
                ]);
            }

            $user_ids = $this->getSubIds($sub_user_id);
            $where[] = ['settling_day', '>=', $time_start];
            $where[] = ['settling_day', '<=', $time_end];
            $obj = DB::table('stores')->where('pid', '=', 0)->whereIn('user_id', $user_ids)->select('id','store_id', 'store_name'); // 门店分页
            $this->t = $obj->paginate(10)->total();
            $store = $this->page($obj)->get();
            $array=array();
            foreach($store as $k=>$v){
                $p_stores = DB::table('stores')->where('pid', $v->id)->select('store_id')->get(); // 查找总店下的分店
                if(!empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                    $store_ids[0] = $v->store_id;
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $store_ids[] = $v1['store_id'];
                    }
                }else{
                    $store_ids[0] = $v->store_id;
                }
                if(empty($company_id)){
                    $way=DB::table('store_pay_ways')->where('store_id',$v->store_id)->select('company')->distinct()->get();
                    foreach($way as $key=>$val){
                        $total_amount= DB::table('company_day_commission')->where($where)->whereIn('store_id', $store_ids)->where('user_id', $sub_user_id)->where('company', $val->company)->sum('total_amount');
                        $item=array('store_id'=>$v->store_id,'store_name'=>$v->store_name,'company'=>$val->company,'total_amount'=>$total_amount);
                        $array[]=$item;
                    }
                }else{
                    $total_amount= DB::table('company_day_commission')->where($where)->whereIn('store_id', $store_ids)->where('user_id', $sub_user_id)->where('company', $company_id)->sum('total_amount');
                    $item=array('store_id'=>$v->store_id,'store_name'=>$v->store_name,'company'=>$company_id,'total_amount'=>$total_amount);
                    $array[]=$item;
                }
                unset($store_ids);
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine()
            ]);
        }
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($array);
    }


    //门店交易量
    public function volume(Request $request)
    {

        try {
            $user = $this->parseToken(); //用户信息
            $user_id = $request->get('user_id', '');
            $type = $request->get('type', '1'); //排序：1-交易笔数,由大到小;2-交易笔数由小到大;
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');

            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => '时间筛选不能超过' . $day . '天'
                ]);
            }
            //限制时间
            if (empty($time_end)) {
                $time_end = date('Y-m-d H:i:s', time());

            } else {
                if ($time_start != $time_end) {
                    $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                    if (!$date) {
                        return json_encode([
                            'status' => 2,
                            'message' => '开始时间不能超过结束时间'
                        ]);
                    }
                }
                $time_end = "$time_end 23:59:59";
            }
            $time_start = "$time_start 00:00:00";




            $user_ids = [];
            if ($user_id) {
//                $user_ids = [
//                    ['user_id' => $user_id]
//                ];
                $user_ids = $this->getSubIds($user_id);
            } else {
                $user_ids = $this->getSubIds($user->user_id);
            }
            if ($type == "1") {
                $sort = 'desc';
                $order_field = "count_order";
            } else {
                $sort = 'asc';
                $order_field = "count_order";
            }

            if (env('DB_D1_HOST')) {
                $Stores_obj = DB::connection("mysql_d1")->table('stores');
            } else {
                $Stores_obj = DB::table('stores');
            }
            $obj = $Stores_obj->select([
                'stores.store_name',
                'stores.store_id',
                'stores.store_short_name',
                'stores.people_phone',
                DB::raw("COUNT(`o`.`id`) as `count_order`")
            ])
                ->leftJoin('orders as o', function($join) use($time_start,$time_end){
                    $join->on('stores.store_id', '=', 'o.store_id');
                    $join->where('o.created_at', '>', "$time_start");
                    $join->where('o.created_at', '<', "$time_end");
                })
//                ->where('o.pay_status', 1)
//                ->where('o.created_at', '>', $time_start)
//                ->where('o.created_at', '<', $time_end)
                ->groupBy('stores.store_id')
                ->orderBy(DB::raw($order_field), $sort);
            $this->t = $obj->paginate(10)->total();
            $data = $this->page($obj)->get();
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage().' | '.$exception->getFile().' | '.$exception->getLine()
            ]);
        }

        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($data);
    }


//    public function ranking(Request $request)
//    {
//
//        try {
//            $user = $this->parseToken();//
//            $type = $request->get('type', '1');//1 交易笔数 由大到小
//            $month = $request->get('month', '');
//
//
//            if (env('DB_D1_HOST')) {
//                $obj = DB::connection("mysql_d1")->table("stores");
//            } else {
//                $obj = DB::table('stores');
//            }
//
//            //1 交易笔数
//            if ($type == "1" || $type == "2") {
//                $sort = 'desc';
//                if ($type == "2") {
//                    $sort = 'asc';
//                }
//
//                $obj = $obj->join('store_month_counts', 'stores.store_id', 'store_month_counts.store_id')
//                    ->where('store_month_counts.month', $month)
//                    ->orderBy('store_month_counts.total_count', $sort)
//                    ->select('store_month_counts.*', 'stores.store_name');
//            } else {
//                $sort = 'desc';
//                if ($type == "4") {
//                    $sort = 'asc';
//                }
//                $obj = $obj->join('store_month_counts', 'stores.store_id', 'store_month_counts.store_id')
//                    ->where('store_month_counts.month', $month)
//                    ->orderBy('store_month_counts.total_amount', $sort)
//                    ->select('store_month_counts.*', 'stores.store_name');
//
//            }
//
//
//            $this->t = $obj->count();
//            $data = $this->page($obj)->get();
//            $this->status = 1;
//            $this->message = '数据返回成功';
//            return $this->format($data);
//
//
//        } catch (\Exception $exception) {
//            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
//        }
//
//    }


    //打款查询
    public function dk_select(Request $request)
    {

        try {
            $user = $this->parseToken();//
            $store_id = $request->get('store_id', '');//1 交易笔数 由大到小
            $time = $request->get('time', '');
            $company = $request->get('company', '');

            $check_data = [
                'company' => '通道类型',
                'time' => '打款时间',
                'store_id' => '门店ID',

            ];

            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $store = Store::where('store_id', $store_id)
                ->select('store_name')
                ->first();
            if (!$store) {
                return json_encode(['status' => 2, 'message' => '门店ID不存在']);

            }
            $store_name = $store->store_name;

            return json_encode([
                'status' => 1,
                'message' => '查询成功',
                'data' => [
                    'store_name' => $store_name,
                    'time' => $time,
                    'total_amount' => '0.01',
                    'dk_time' => $time,
                    'dk_desc' => '打款成功',

                ]
            ]);


        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }

    }


    //代理商上级查询
    public function select_pid_user(Request $request)
    {
        try {
            $token = $this->parseToken();
            $users = $this->getSubIds($token->user_id); //获取所有下级
            $user_name = $request->get('user_name', '');
            $user = DB::table('users')
                ->whereIn('id', $users)->where(function ($query) use($user_name){
                $query->where('name', 'like', '%' . $user_name . '%')->orWhere("phone","=",$user_name);
            })->select('level', 'id', 'name', 'phone', 'pid', 's_code', 'money')->get();
            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在'
                ]);
            }
            $user_obj = $user;
            foreach($user as $k=>$v){
                $user_name = $user[$k]->name . '(' . $user[$k]->phone .')';
                $pid = $user[$k]->pid;
                for ($i = 0; $i < $user[$k]->level + 2; $i++) {
                    if ($pid == 0) {
                        break;
                    }
                    $user1 = User::where('id', $pid)
                        ->select('level', 'id', 'name', 'phone', 'pid', 's_code', 'money')
                        ->first();

                    $pid = $user1->pid;
                    $user_name = $user_name . '=>' . $user1->name . '(' . $user1->phone . ')';
                }
                $array[$k]=$user_name;
                unset($user_name);
            }
            return json_encode([
                'status' => 1,
                'message' => '数据返回成功',
                'data' => [
                    'info' => $array??[],
                    'user_info' => $user_obj
                ]
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage().' | '.$exception->getLine()
            ]);
        }
    }


    //清除通道
    public function clear_ways_type(Request $request)
    {
        try {
            $company = $request->get('company', '');
            $store_id = $request->get('store_id', '');
            $user = $this->parseToken();

            $user = User::where('id', $user->user_id)->first();
            $hasPermission = $user->hasPermissionTo('清除通道');
            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限清除通道']);
            }

            //传化
            if ($company == "tfpay") {
                $TfStore = TfStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }

            //支付宝
            if ($company == "alipay") {
                $AlipayAppOauthUsers = AlipayAppOauthUsers::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }

            //和融通
            if ($company == "herongtong") {
                $TfStore = HStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }

            //新大陆
            if ($company == "newland") {
                $NewLandStore = NewLandStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }

            //快钱
            if ($company == "mybank") {
                $MyBankStore = MyBankStoreTem::where('OutMerchantId', $store_id)->delete();
                $MyBankStore = MyBankStore::where('OutMerchantId', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }

            //微信官方
            if ($company == "weixin") {
                $NewLandStore = WeixinStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);
            }

            //随行付
            if ($company == "vbill") {
                VbillStore::where('store_id', $store_id)->delete();
                StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);
            }

	        //多啦宝
            if ($company == "dlb") {
                DlbStoreUpload::where('store_id', $store_id)->delete();
                DlbStore::where('store_id', $store_id)->delete();
                StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);
            }

            //邮政
            if ($company == "lianfuyoupay") {
                $lianFuYouPayStores = LianfuyoupayStores::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => 1,
                    'message' => '邮政通道删除成功'
                ]);
            }

            //葫芦天下
            if ($company == "hltx") {
                $HltxStore = HltxStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => 1,
                    'message' => 'hl删除成功'
                ]);
            }

            //随行付a
            if ($company == "vbilla") {
                VbillaStore::where('store_id', $store_id)->delete();
                StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);
            }

	        //海科融通
            if ($company == "hkrt") {
                $HkrtStore = HkrtStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => '1',
                    'message' => '删除成功'
                ]);
            }

            //易生支付
            if ($company == "easypay") {
                EasypayStore::query()->where('store_id', $store_id)->delete();
                StorePayWay::query()->where('company', $company)->where('store_id', $store_id)->delete();
                EasypayConfig::where('config_id', '1234')->update(['getSignKey' => '']); //清除签名密钥

                return json_encode([
                    'status' => '1',
                    'message' => '删除成功'
                ]);
            }

            if ($company == "easypaya") {
                EasypayaStore::query()->where('store_id', $store_id)->delete();
                StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                EasypayConfig::where('config_id', '1234')->update(['getSignKey' => '']); //清除签名密钥

                return json_encode([
                    'status' => '1',
                    'message' => '删除成功'
                ]);
            }

            //联动优势
            if ($company == "linkage") {
                LinkageStores::where('store_id', $store_id)->delete();
                StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => '1',
                    'message' => '删除成功'
                ]);
            }

            //微信官方
            if ($company == "weixina") {
                $NewLandStore = WeixinaStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();

                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);
            }

            return json_encode([
                'status' => 2,
                'message' => '暂不支持清除此通道'
            ]);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '2',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 根据门店ID查看收银员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function merchant_lists(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $name = $request->get('name', '');

            $where = [];


            if ($name) {
                $where[] = ['merchants.name', 'like', '%' . $name . '%'];
            }


            if ($store_id) {
                $where[] = ['stores.store_id', '=', $store_id];
            }


            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("merchant_stores");
            } else {
                $obj = DB::table('merchant_stores');
            }

            $obj->join('merchants', 'merchant_stores.merchant_id', '=', 'merchants.id')
                ->join('stores', 'merchant_stores.store_id', '=', 'stores.store_id')
                ->where($where)
                ->select('merchants.is_mini_send','stores.store_name', 'merchants.id as merchant_id', 'merchants.name', 'merchants.phone', 'merchants.type', 'merchants.logo', 'merchants.wx_logo');

            $this->t = $obj->count();
            $data = $this->page($obj)->get();

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }

        /**
     * 根据门店ID查看充值记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function rataDetail(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $where = [];


            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
            }
            $store= DB::table('stores')->where($where)->first();


            $obj = DB::table('fullmoney_log');

            $obj->where($where)->select('*');

            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('updated_at', 'desc')->get();
            $data=json_decode($data,true);
            foreach($data as $key=>$val){
                $data[$key]['store_name']=$store->store_name;
                $data[$key]['created_at']=date("Y-m-d H:i:s",$val['created_at']);
                if($val['status']==2){
                    $data[$key]['status']='支付成功';
                }else{
                    $data[$key]['status']='支付失败';
                }
            }
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }

    public function feeDetail3(Request $request){
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $obj = DB::table('service_bill_log');
            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
                $obj->where($where);
            }
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('settling_day', 'desc')->get();
            $data = json_decode($data, true);
            foreach($data as &$v){
                $v['before_money'] = bcdiv($v['before_money'],100,2);
                $v['end_money'] = bcdiv($v['end_money'],100,2);
                $v['count'] = bcdiv($v['service_fee'],100,2);
                $v['order_count'] = bcdiv($v['total_fee'],100,2);
            }
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }

      /**
     * 根据门店ID查看扣费记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function feeDetail(Request $request){
        // print_r(2);die;
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');

            $where = [];

            // $obj = DB::table('skill_ratastore');
            $obj = DB::table('service_day_money as r');
            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
            }
            // $store = DB::table('stores')->where($where)->first();
            // dump($store);die;
            // $childstore = DB::table('stores')->where('pid', $store->id)->first();
            // if(!empty($childstore)){
            //     $stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get();
            //     $stores = json_decode($stores, true);
            //     foreach($stores as $k => $v){
            //         $arr[$k] = $v['store_id'];
            //     }
            //     $obj->whereIn('store_id',$arr)->select('*');

            // }else{
                // $obj->where($where)->select('*');
            // }
            $obj->where($where)->select('*');
                // ->select('r.store_id')
                // ->leftJoin('stores', 'r.sotre_id', '=', 'stores.sotre_id');

            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('settling_day', 'desc')->get();

            $data = json_decode($data, true);
            // dump($data);die;

            // foreach($data as $k => $v){
                // $data[$k]['count'] = $store->store_name;
                // if($val['status'] == 1){
                //     $data[$k]['status'] = '扣费成功';
                // }
            // }

            // foreach($data as $key => $val){
            //     $data[$key]['store_name']=$store->store_name;
            //     if($val['status']==1){
            //         $data[$key]['status']='扣费成功';
            //     }
            // }
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 添加收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_merchant(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $type = $request->get('type', '2');
            $name = $request->get('name', '');
            $phone = $request->get('phone', '');
            $data = $request->except(['token']);
            $password = $request->get('password', '');
            $stores = Store::where('store_id', $store_id)
                ->first();
            if ($password == "") {
                $password = '000000';
            }
            if ($name == "") {
                $this->status = 2;
                $this->message = '姓名必填';
                return $this->format();
            }

            if ($phone == "") {
                $this->status = 2;
                $this->message = '手机号必填';
                return $this->format();
            }


            if (!$stores) {
                $this->status = 2;
                $this->message = '门店不存在';
                return $this->format();
            }


            $rules = [
                'phone' => 'required|min:11|max:11',
            ];
            $validator = Validator::make($data, $rules);
            if ($validator->fails()) {
                return json_encode([
                    'status' => 2,
                    'message' => '手机号位数不正确',
                ]);
            }


            //验证密码
            if (strlen($password) < 6) {
                return json_encode([
                    'status' => 2,
                    'message' => '密码长度不符合要求'
                ]);
            }



            // $pash = $request->path();
            // $pass = $request->get('pass', '');
            // $pass = substr(base64_decode($pass), 0, -5);

            // $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            // $pass_verify = json_decode($pass_verify, true);
            // print_r( $pass );die;
            // if( $pass_verify['status'] == '1'){
                // $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
                // $remark = '门店添加收银员: 门店id: ' . $store_id . '添加收银员';
                // $this->operation_log( $this->parseToken()->user_id, 16, $remark , $pass_id );
            // }else{
            //     return json_encode(['status' => 2, 'message' => '验证不通过', 'data' => []]);
            // }




            $rules = [
                'phone' => 'required|unique:merchants',
            ];
            $validator = Validator::make($data, $rules);
            if ($validator->fails()) {

                return json_encode([
                    'status' => 2,
                    'message' => '手机号已经注册'
                ]);
            } else {
                $dataIN = [
                    'pid' => $stores->merchant_id ? $stores->merchant_id : "0",
                    'type' => $type,
                    'name' => $name,
                    'email' => '',
                    'password' => bcrypt($password),
                    'phone' => $phone,
                    'user_id' => $stores->user_id,//推广员id
                    'config_id' => $stores->config_id,
                    'wx_openid' => '',
                    'is_mini_send' => $request->get('is_mini_send')
                ];
                $insert = Merchant::create($dataIN);
                $merchant_id = $insert->id;
            }

            MerchantStore::create([
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
            ]);


            $this->status = 1;
            $this->message = '收银员添加成功';
            return $this->format();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 绑定收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bind_merchant(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id');
            $type = $request->get('type');
            $merchant_id = $request->get('merchant_id');


            $check_data = [
                'store_id' => '门店ID',
                'type' => '角色类型',
                'merchant_id' => '收银员',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $MerchantStore = MerchantStore::where('store_id', $store_id)
                ->where('merchant_id', $merchant_id)
                ->first();

            if ($MerchantStore) {
                return json_encode([
                    'status' => 2,
                    'message' => '收银员已经绑定无需重复绑定'
                ]);
            }

            MerchantStore::create([
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'type' => $type,
            ]);


            $this->status = 1;
            $this->message = '收银员绑定成功';
            return $this->format();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 修改收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function up_merchant(Request $request)
    {
        try {
            $merchant = $this->parseToken();
            $merchant_id = $request->get('merchant_id');
            $store_id = $request->get('store_id');
            $name = $request->get('name', '');
            $password = $request->get('password', '');
            $data = $request->except(['token', 'merchant_id', 'store_id', 'password']);


            if ($password == "") {
                $password = '000000';
            }
            if ($name == "") {
                $this->status = 2;
                $this->message = '姓名必填';
                return $this->format();
            }


            if ($password && $password != '000000') {
                //验证密码
                if (strlen($password) < 6) {
                    return json_encode([
                        'status' => 2,
                        'message' => '密码长度不符合要求'
                    ]);
                }

                $data['password'] = bcrypt($password);
            }

            $isMiniSend = $request->get('is_mini_send', '');
            if ($isMiniSend != '') {
                $data['is_mini_send'] = $isMiniSend;
            }
            $dataIN = $data;

            $Merchant = Merchant::where('id', $merchant_id)
                ->select('phone')
                ->first();

            $phone = $Merchant->phone;
            if ($phone != $data['phone']) {
                $rules = [
                    'phone' => 'required|unique:merchants',
                ];
                $validator = Validator::make($data, $rules);
                if ($validator->fails()) {

                    return json_encode([
                        'status' => 2,
                        'message' => '手机号已经注册'
                    ]);
                }
            }

            if(strlen($data['phone']) !=11){
                return json_encode([
                    'status' => 2,
                    'message' => '手机号码必须11位'
                ]);
            }

            Merchant::where('id', $merchant_id)
                ->update($dataIN);

            $this->status = 1;
            $this->message = '收银员修改成功';

            return $this->format();
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }


    /**
     * 删除收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del_merchant(Request $request){

        // if( $this->parseToken()->type == 'user' && $this->parseToken()->user_id == 1 ){

        // }else{
        //     $this->status = -1;
        //     $this->message = '暂无权限删除';
        //     return $this->format();
        // }


        try {
            $user = $this->parseToken();
            $merchant_id = $request->get('merchant_id', '');
            $store_id = $request->get('store_id', '');

            $check_data = [
                'merchant_id' => '收银员',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }


            $user = User::where('id', $user->user_id)->first();
            $hasPermission = $user->hasPermissionTo('删除收银员');

            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限']);
            }


            if ($merchant_id == "") {
                $this->status = 2;
                $this->message = '请选择收银员';
                return $this->format();
            }
            $Merchant = Merchant::where('id', $merchant_id)->first();

            if (!$Merchant) {
                $this->status = 2;
                $this->message = '收银员不存在';
                return $this->format();
            }



            // $pash = $request->path();
            // $pass = $request->get('pass', '');
            // $pass = substr(base64_decode($pass), 0, -5);

            // $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            // $pass_verify = json_decode($pass_verify, true);
            // if( $pass_verify['status'] == '1'){
            //     $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
            //     $remark = '门店删除收银员: 门店id: ' . $store_id . '删除收银员id: ' . $merchant_id;
            //     $this->operation_log( $this->parseToken()->user_id, 17, $remark , $pass_id );
            // }else{
            //     return json_encode(['status' => 2, 'message' => '验证不通过', 'data' => []]);
            // }




            if ($store_id) {
                //删除收银员关联表
                $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                    ->where('store_id', $store_id)
                    ->delete();
            } else {
                //删除收银员关联表
                $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                    ->delete();
            }

            $Merchant->delete();


            $this->status = 1;
            $this->message = '收银员删除成功';
            return $this->format();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 单个收银员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function merchant_info(Request $request)
    {
        try {
            $merchant = $this->parseToken();
            $merchant_id = $request->get('merchant_id');
            $store_id = $request->get('store_id', '');

            $check_data = [
                'merchant_id' => '收银员',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $data = Merchant::where('id', $merchant_id)->first();
            if (!$data) {
                $this->status = 2;
                $this->message = '收银员不存在';
                return $this->format();
            }

            //门店id存在
            if ($store_id) {
                //收银员的收款聚合码
                $data->pay_qr = url('/qr?store_id=' . $store_id . '&merchant_id=' . $merchant_id . '');
            }

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }

    /**
     * 代理数据统计
     * 2022-04-14 14:11
     */
    public function merchant_turnover(Request $request){
        try {
            $token = $this->parseToken();
            $user = $this->parseToken(); //用户信息
            $token_user_id = $token->user_id;
            $p=$request->get('p', '');
            $l=$request->get('l', '');

            $curHdIndex = $request->get('curHdIndex', '');
            $pay_type = $request->get('pay_type', '');

            $login_user = User::where('id', $token_user_id)
                ->where('is_delete', '=', '0')
                ->first();
            if (!$login_user) {
                $this->status = '2';
                $this->message = '当前登录状态异常';
                return $this->format();
            }
            $user_ids = $this->getSubIds($token_user_id); // 获取代理下的用户
            $obj = DB::table('stores')->whereIn('user_id', $user_ids)->where('pid', '=', 0)->select('store_id', 'store_name', 'id'); // 获取代理下的门店
            $this->t = $obj->count();
            $store_ids = $this->page($obj)->get();
            $store_ids = json_decode($store_ids, true);

            if($curHdIndex == 1){ // 今日
                $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
                $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];

                foreach($store_ids as $key => $val){
                    $p_stores = DB::table('stores')->where('pid', $val['id'])->select('store_id')->get();
                    // dump($p_stores);die;
                    $store_arr['store_id'] = $val['store_id'];
                    $store_arr['store_name'] = $val['store_name'];

                    if( !empty($p_stores[0]->store_id) ){
                        $p_store_data[0] = $val['store_id'];
                        $p_stores = json_decode($p_stores, true);
                        foreach($p_stores as $k1 => $v1){
                            $p_store_data[] = $v1['store_id'];
                        }
                        // dump($p_store_data);die;
                        $store_arr['total_amount'] = Order::whereIn('store_id', $p_store_data)->where($where)->where('ways_source',$pay_type)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
                        $store_arr['total_num'] = Order::whereIn('store_id', $p_store_data)->where($where)->where('ways_source',$pay_type)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
                        $store_arr_data[] = $store_arr;
                        unset($p_store_data);
                    }else{
                        $store_arr['total_amount'] = Order::where('store_id', $val['store_id'])->where($where)->where('ways_source',$pay_type)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
                        $store_arr['total_num'] = Order::where('store_id', $val['store_id'])->where($where)->where('ways_source',$pay_type)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
                        $store_arr['commission_money'] = 0;
                        $store_arr_data[] = $store_arr;
                    }
                }
                // dump($store_arr_data);die;
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($store_arr_data);
            }
            if($curHdIndex == 2){ // 昨日
                $where[] = ['settling_day', '>=', date('Y-m-d', strtotime("-1 day"))];
                $where[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            }else if($curHdIndex == 3){ // 上周
                $where[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
                $where[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            }else if($curHdIndex == 4){ // 本月
                $where[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
                $where[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            }else if($curHdIndex == 5){ // 上月
                $where[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
                $where[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            }
            // dump($where);die;
            // dump($store_ids);die;
            foreach($store_ids as $key => $val){
                $p_stores = DB::table('stores')->where('pid', $val['id'])->select('store_id')->get();
                // dump($p_stores);die;
                $store_arr['store_id'] = $val['store_id'];
                $store_arr['store_name'] = $val['store_name'];

                if(!empty($p_stores[0]->store_id) ){
                    $p_store_data[0] = $val['store_id'];
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $p_store_data[] = $v1['store_id'];
                    }
                    if( $pay_type == 'weixin' ){
                        $store_arr['total_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('weixin_amount')->sum('weixin_amount');
                        $store_arr['total_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('weixin_num')->sum('weixin_num');
                    }else if($pay_type == 'alipay'){
                        $store_arr['total_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('alipay_amount')->sum('alipay_amount');
                        $store_arr['total_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('alipay_num')->sum('alipay_num');
                    }

                    $store_arr_data[] = $store_arr;
                    unset($p_store_data);
                }else{
                    if( $pay_type == 'weixin' ){
                        $store_arr['total_amount'] = DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('weixin_amount')->sum('weixin_amount');
                        $store_arr['total_num'] = DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('weixin_num')->sum('weixin_num');
                    }else if($pay_type == 'alipay'){
                        $store_arr['total_amount'] = DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('alipay_amount')->sum('alipay_amount');
                        $store_arr['total_num'] = DB::table('stores_day_count')->where('store_id', $val['store_id'])->where($where)->select('alipay_num')->sum('alipay_num');
                    }
                    $store_arr['commission_money'] = 0;
                    $store_arr_data[] = $store_arr;
                }
            }
            // dump($store_arr_data);die;
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($store_arr_data);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage().' | '.$exception->getFile().' | '.$exception->getLine()
            ]);
        }
    }

    /**
     * 代理数据统计
     * 2022-04-14 14:11
     */
    public function merchant_id_turnover(Request $request){
        try {
            $store_id = $request->get('store_id', ''); // 门店id
            $pay_type = $request->get('pay_type', ''); // 支付方式
            $curHdIndex = $request->get('curHdIndex', ''); // 今日 昨日 上周 本月 上月

            $store = DB::table('stores')->where('store_id', $store_id)->select('id')->first();
            $store_ids = DB::table('stores')->where('pid', $store->id)->select('store_id', 'store_name', 'id')->get();

            $store_ids = json_decode($store_ids, true);

            $p_store_data[0] = $store_id;
            foreach($store_ids as $k1 => $v1){
                $p_store_data[] = $v1['store_id'];
            }
            // dump($p_store_data);die;

            // $where[] = ['store_id', $store_id]; // 门店id

            if($curHdIndex == 1){ // 今日
                $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
                $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];

                $where[] = ['ways_source', $pay_type];

                foreach($p_store_data as $key => $val){
                    // $data['total_amount'] = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount'); // 交易金额
                    $data['ture_amount'] = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->select('total_amount')->sum('total_amount'); // 实际收款
                    // $data['order_num'] = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount'); // 订单笔数
                    // $data['refund_amount'] = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount'); // 退款金额
                    // $data['refund_num'] = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->count('refund_amount'); // 退款笔数
                    $obj=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select();
                    $this->t=$obj->count();
                    $data['order_list'] =$this->page($obj)->get();

                }

                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($data);
            }
            if($curHdIndex == 2){ // 昨日
                $where[] = ['settling_day', '>=', date('Y-m-d', strtotime("-1 day"))];
                $where[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];

                foreach($p_store_data as $key => $val){
                    // dump($where);
                    if( $pay_type == 'weixin' ){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('weixin_amount')->sum('weixin_amount'); // 实际收款
                    }else if($pay_type == 'alipay'){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('alipay_amount')->sum('alipay_amount'); // 实际收款
                    }
                    // dump($where);die;
                    // $data['total_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_amount')->sum('store_amount'); // 交易金额

                    // $data['order_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_order_count')->count('store_order_count'); // 订单笔数
                    // $data['refund_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount'); // 退款金额
                    // $data['refund_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_order_num')->count('refund_order_num'); // 退款笔数
                    // $data['ture_amount'] = $data['total_amount'] - $data['refund_amount']; // 实际收款

                    $where = [];
                    $where[] = ['created_at', '>=', date('Y-m-d', strtotime("-1 day")).' 00:00:00'];
                    $where[] = ['created_at', '<=', date('Y-m-d', strtotime("-1 day")).' 23:59:59'];

                    $where[] = ['ways_source', $pay_type];
                    // dump($where);die;

                    $obj=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select();
                    $this->t=$obj->count();
                    $data['order_list'] =$this->page($obj)->get();
                    // $data['order_list'] = Order::where('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select()->get('store_amount');
                }
            }else if($curHdIndex == 3){ // 上周
                $where[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
                $where[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];

                foreach($p_store_data as $key => $val){

                    if( $pay_type == 'weixin' ){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('weixin_amount')->sum('weixin_amount'); // 实际收款
                    }else if($pay_type == 'alipay'){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('alipay_amount')->sum('alipay_amount'); // 实际收款
                    }
                    // dump($where);die;
                    // $data['total_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_amount')->sum('store_amount'); // 交易金额

                    // $data['order_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_order_count')->count('store_order_count'); // 订单笔数
                    // $data['refund_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount'); // 退款金额
                    // $data['refund_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_order_num')->count('refund_order_num'); // 退款笔数
                    // $data['ture_amount'] = $data['total_amount'] - $data['refund_amount']; // 实际收款

                    $where = [];
                    $where[] = ['created_at', '>=', date('Y-m-d', strtotime('last week')).' 00:00:00'];
                    $where[] = ['created_at', '<=', date('Y-m-d', strtotime('this week -1 day')).' 23:59:59'];

                    $where[] = ['ways_source', $pay_type];

                    $obj=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select();
                    $this->t=$obj->count();
                    $data['order_list'] =$this->page($obj)->get();
                    // $data['order_list'] = Order::where('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select()->get('store_amount');
                }
            }else if($curHdIndex == 4){ // 本月
                $where[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
                $where[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];

                foreach($p_store_data as $key => $val){

                    if( $pay_type == 'weixin' ){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('weixin_amount')->sum('weixin_amount'); // 实际收款
                    }else if($pay_type == 'alipay'){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('alipay_amount')->sum('alipay_amount'); // 实际收款
                    }
                    // dump($where);die;
                    // $data['total_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_amount')->sum('store_amount'); // 交易金额

                    // $data['order_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_order_count')->count('store_order_count'); // 订单笔数
                    // $data['refund_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount'); // 退款金额
                    // $data['refund_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_order_num')->count('refund_order_num'); // 退款笔数
                    // $data['ture_amount'] = $data['total_amount'] - $data['refund_amount']; // 实际收款

                    $where = [];
                    $where[] = ['created_at', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
                    $where[] = ['created_at', '<=', date('Y-m-d', strtotime("-1 day")).' 23:59:59'];

                    $where[] = ['ways_source', $pay_type];

                    $obj=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select();
                    $this->t=$obj->count();
                    $data['order_list'] =$this->page($obj)->get();
                    // $data['order_list'] = Order::where('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select()->get('store_amount');
                }
            }else if($curHdIndex == 5){ // 上月
                $where[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
                $where[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];

                foreach($p_store_data as $key => $val){

                    if( $pay_type == 'weixin' ){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('weixin_amount')->sum('weixin_amount'); // 实际收款
                    }else if($pay_type == 'alipay'){
                        $data['ture_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('alipay_amount')->sum('alipay_amount'); // 实际收款
                    }
                    // dump($where);die;
                    // $data['total_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_amount')->sum('store_amount'); // 交易金额

                    // $data['order_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select('store_order_count')->count('store_order_count'); // 订单笔数
                    // $data['refund_amount'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount'); // 退款金额
                    // $data['refund_num'] = DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->select('refund_order_num')->count('refund_order_num'); // 退款笔数
                    // $data['ture_amount'] = $data['total_amount'] - $data['refund_amount']; // 实际收款

                    $where = [];
                    $where[] = ['created_at', '>=', date('Y-m-01', strtotime('-1 month')).' 00:00:00'];
                    $where[] = ['created_at', '<=', date('Y-m-t', strtotime('-1 month')).' 23:59:59'];

                    $where[] = ['ways_source', $pay_type];

                    $obj=Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select();
                    $this->t=$obj->count();
                    $data['order_list'] =$this->page($obj)->get();
                    // $data['order_list'] = Order::where('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1, 6])->select()->get('store_amount');
                }
            }

            // dump($p_store_data);die;


            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage().' | '.$exception->getFile().' | '.$exception->getLine()
            ]);
        }
    }

    /**
     * 机构关联商户函数
     */
    public function mechanism_merchant_add(Request $request){
        try {
            //获取参数
            $store_id = $request->get('store_id', '');
            $mechanism_id = $request->get('mechanism_id', '');
            //判断必要传参
            if(empty($store_id)){
                $this->status = 2;
                $this->message = '参数错误';
                return $this->format();
            }
            if(empty($mechanism_id)){
                $this->status = 2;
                $this->message = '请输入机构号, 刷新重试';
                return $this->format();
            }



            $pash = $request->path();
            $pass = $request->get('pass', '');
            $pass = substr(base64_decode($pass), 0, -5);

            $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            $pass_verify = json_decode($pass_verify, true);
            // print_r( $this->parseToken() );die;
            if( $pass_verify['status'] == '1'){
                $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
                $remark = '门店关联机构号: 门店id: ' . $store_id . '关联机构号';
                $this->operation_log( $this->parseToken()->user_id, 15, $remark , $pass_id );
            }else{
                return json_encode(['status' => 2, 'message' => '验证不通过', 'data' => []]);
            }

            $store=Store::query()->where("store_id",$store_id)->first();
            if(empty($store)){
                $this->status = 2;
                $this->message = '店铺不存在';
                return $this->format();
            }else if($store->pid>0){
                $this->status = 2;
                $this->message = '分店不允许关联机构号';
                return $this->format();
            }

            //查询机构
            $mechanism_merchant = Db::table('mechanism_merchant')->where(['mechanism_id' => $mechanism_id, 'merchant_id' => $store_id ])->first();
            if($mechanism_merchant){
                $this->status = 2;
                $this->message = '该机构号已添加';
                return $this->format();
            }else{
                $where = [];
                $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
                $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
                    //机构关联数据
                $data=array(
                    'mechanism_id'=>$mechanism_id,
                    'merchant_id' => $store_id,
                    'now_time' => time(),
                );
                DB::table('mechanism_merchant')->insert($data);

                $this->status = 1;
                $this->message = '机构号添加成功';
                return $this->format();
            }
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }

    // 代理门店统计
    public function user_store_count(Request $request){
        $time_start = $request->get('time_start', '');
        $time_end = $request->get('time_end', '');

        $user_id = $request->get('user_id', '');

        if(empty($user_id)){
            $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
            $is_search = 1;
        }else{
            $is_search = 2;
        }

        $user_ids = $this->getSubIds($user_id); // 所有下级代理

        if(empty($time_start)){
            $time_start = date('Y-m-d', strtotime("-1 day"));
        }
        if(empty($time_end)){
            $time_end = date('Y-m-d', strtotime("-1 day"));
        }
        if ($time_start != $time_end) {
            $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
            if (!$date) {
                return json_encode([
                    'status' => 2,
                    'message' => '开始时间不能超过结束时间'
                ]);
            }
        }
        //限制时间
        $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
        $day = 31;
        if ($date > $day) {
            return json_encode([
                'status' => 2,
                'message' => "时间筛选不能超过 $day 天"
            ]);
        }
        if($time_start >= date("Y-m-d",strtotime("+1 day"))){
            return json_encode([
                'status' => 2,
                'message' => '开始时间不能超过今天'
            ]);
        }

        if($time_start >= date('Y-m-d', time()) || $time_end >= date('Y-m-d', time()) ){
            return json_encode([
                'status' => 2,
                'message' => '不支持查询今天的统计数据'
            ]);
        }

        $where[] = ['created_at', '>=', date('Y-m-d 00:00:00', time())];
        $where[] = ['created_at', '<=', date('Y-m-d 23:59:59', time())];

        $where1[] = ['settling_day', '>=', $time_start];
        $where1[] = ['settling_day', '<=', $time_end];

        $storearr=[];
        if($is_search == 2){
            $obj = DB::table('users')->where(['id' => $user_id])->where(['is_delete' => 0])->select('id', 'name', 'phone'); // 下级一级的代理列表
        }else{
            $obj = DB::table('users')->where(['id' => $user_id])->orwhere(['pid' => $user_id])->where(['is_delete' => 0])->select('id', 'name', 'phone'); // 下级一级的代理列表
        }
        $this->t = $obj->paginate()->total();
        $users_list = $this->page($obj)->get();

        if( $users_list[0]->id !== 1 ){
            foreach($users_list as $key => $val){
                $user_ids = $this->getSubIds($val->id); // 所有下级代理
                $store_list = DB::table('stores')->whereIn('user_id', $user_ids)->where('pid', 0)->select('store_id', 'store_name', 'people', 'people_phone', 'id')->get(); // 总店列表
                foreach ($store_list as $r=>$q){
                    unset($store_ids);
                    $p_stores = DB::table('stores')->where('pid', $q->id)->select('store_id')->get(); // 查找总店下的分店
                    if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                        $store_ids[0] = $q->store_id;
                        $p_stores = json_decode($p_stores, true);
                        foreach($p_stores as $k1 => $v1){
                            $store_ids[] = $v1['store_id']; // 总店+分店
                        }
                    }else{
                        $store_ids[0] = $q->store_id; // 总店+分店
                    }
                    // if($time_start >= date('Y-m-d', time())){ // 查今天
                    //     $total_amount = DB::table('orders')->whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->sum('total_amount');
                    // }else{ // 查每日汇总表
                        $total_amount = DB::table('company_day_commission')->where($where1)->where('user_id', $user_id)->whereIn('store_id', $store_ids)->sum('total_amount');
                    // }
                    $storearr[]=array('user_name'=>$val->name,'user_phone'=>$val->phone . "\t",'store_id'=>$q->store_id . "\t",'store_name'=>$q->store_name,'store_people'=>$q->people,'store_phone'=>$q->people_phone . "\t",'total_amount'=>$total_amount);
                }
            }
        }else{
            $first_user=DB::table('users')->where(['id' => $user_id])->select('id', 'name', 'phone')->first(); // 下级一级的代理列表
            $store_list = DB::table('stores')->where('user_id', $user_id)->where('pid', 0)->select('store_id', 'store_name', 'people', 'people_phone', 'id')->get(); // 总店列表

            foreach ($store_list as $r=>$q){
                unset($store_ids);
                $p_stores = DB::table('stores')->where('pid', $q->id)->select('store_id')->get(); // 查找总店下的分店
                if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                    $store_ids[0] = $q->store_id;
                    $p_stores = json_decode($p_stores, true);
                    foreach($p_stores as $k1 => $v1){
                        $store_ids[] = $v1['store_id']; // 总店+分店
                    }
                }else{
                    $store_ids[0] = $q->store_id; // 总店+分店
                }
                // if($time_start >= date('Y-m-d', time())){ // 查今天
                //     $total_amount = DB::table('orders')->whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->sum('total_amount');
                // }else{ // 查每日汇总表
                    $total_amount = DB::table('company_day_commission')->where($where1)->where('user_id', $user_id)->whereIn('store_id', $store_ids)->sum('total_amount');
                // }
                $storearr[]=array('user_name'=>$first_user->name,'user_phone'=>$first_user->phone . "\t",'store_id'=>$q->store_id . "\t",'store_name'=>$q->store_name,'store_people'=>$q->people,'store_phone'=>$q->people_phone . "\t",'total_amount'=>$total_amount);
            }
        }
        $data = array_column($storearr, 'total_amount');
        array_multisort($data, SORT_DESC, $storearr); // 代理按金额排序

        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($storearr);
    }

    //渠道商户列表
    public function company_all_store_list (Request $request)
    {
        $company = $request->get('company');
        if (empty($company)) {
            return json_encode([
                'status' => 2,
                'message' => "请选择通道！"
            ]);
        }
        $rule = DB::table('company_rule')->where(['code' => $company])->first();
        if (empty($rule)) {
            return json_encode([
                'status' => 2,
                'message' => "当前通道不支持！"
            ]);
        }
        $obj = DB::table($rule->model)
            ->select('stores.store_id','stores.store_name',$rule->mch_num_as.' as mch_id', 'stores.people_phone', 'stores.people', 'users.name')
            ->leftJoin('stores', 'stores.store_id' , '=', $rule->model.'.store_id')
            ->leftJoin('users', 'users.id', '=', 'stores.user_id');
        if ($request->get('export') == 1) {
            if ($company) {
                $where_desc = '通道：' . $rule->name;
            }
            $mergedArray = json_decode(json_encode($obj->get()),true);
            $filename = '通道商户导出.csv';
            $s_array = ['筛选条件：' . $where_desc];
            $tileArray = ['门店ID', '门店名称', '商户号', '手机号码', '联系人','所属代理'];
            return $this->exportToExcel($filename, $s_array, $tileArray, $mergedArray);
        } else {
            $this->t = $obj->count();
            $data = $this->page($obj)->get();
        }
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($data);
    }

    //导出
    public function exportToExcel($filename, $s_array, $tileArray = [], $dataArray = [])
    {
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename);
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, $s_array);
        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($dataArray as $item) {
            if(!empty($item['mch_id'])){
                $item['mch_id'] = $item['mch_id']. "\t";
            }
            if(!empty($item['people_phone'])){
                $item['people_phone'] = $item['people_phone']. "\t";
            }
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
    }

    public function store_company_model_list(Request $request)
    {
        $obj = DB::table('stores')
            ->select('stores.store_id','stores.store_name','users.name','store_pay_ways.company','store_all_pay_way_lists.company_desc','company_config.model','stores.is_quota')
            ->leftJoin('store_pay_ways', 'stores.store_id' , '=', 'store_pay_ways.store_id')
            ->leftJoin('company_config', 'stores.store_id', '=', 'company_config.store_id')
            ->leftJoin('store_all_pay_way_lists', 'store_pay_ways.company', '=', 'store_all_pay_way_lists.company')
            ->leftJoin('users', 'users.id', '=', 'stores.user_id')
            ->distinct();
        $mergedArray = json_decode(json_encode($obj->get()),true);
        foreach($mergedArray as $k => &$v){

            if($v['is_quota']==1){
                $v['is_quota']='开';
            }else{
                $v['is_quota']='关';
            }
            $model = $v['model'] ?? null;

            if ($model == '1') {
                $v['model_name'] = '服务费模式';
            } else if ($model == '2') {
                $v['model_name'] = '代扣模式';
            } else if ($model == '3') {
                $v['model_name'] = '通道模式';
            } else {
                $v['model_name'] = '预充模式';
            }
        }
        unset($v);
        $filename = '通道模式商户列表.csv';
        $tileArray = ['门店ID', '门店名称','代理名称', '通道','通道名称', '扣费模式' ,'额度开关','扣费模式名称'];
        $s_array = [];
        return $this->exportToExcel($filename, $s_array, $tileArray, $mergedArray);
    }
}